const db = require("../db/index");

//发布文章
exports.publisharticle = (req, res) => {
  const sql0 = "select * from storemember where storeid = ? and memberid = ?";
  db.query(sql0, [req.body.storeid, req.user.id], (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常",
      });
    if (result.length < 1) {
      return res.send({
        code: 403,
        message: "您没有权限，请先加入该库",
      });
    } else {
      db.getConnection(function (err, connection) {
        if (err) {
          return res.send({
            code: 1003,
            message: "数据库异常",
          });
        }
        connection.beginTransaction((err) => {
          //开启事务
          if (err) {
            return res.send({
              code: 1003,
              message: "数据库异常",
            });
          } else {
            let sqlstr = "insert into articles set ?";
            let articleForm = {
              title: req.body.title,
              content: req.body.content,
              annexid: req.body.annexid,
              annexname: req.body.annexname,
              annextype: req.body.annextype,
              auth: req.body.auth,
              authorid: req.user.id,
            };
            connection.query(sqlstr, articleForm, (e, result1) => {
              if (e) {
                res.send({ code: 1003, message: "发布失败，请稍后重试" });
                console.log(e);
                return connection.rollback(() => {
                  console.log("插入失败数据回滚1");
                });
              } else {
                let param = {
                  filetitle: req.body.title,
                  type: 1,
                  isprivate: req.body.isprivate,
                  parentid: req.body.parentid,
                  typeid: result1.insertId,
                  storeid: req.body.storeid,
                  founderid: req.user.id,
                };
                const sql2 = "insert into storefiles set ?";
                connection.query(sql2, param, (e) => {
                  if (e) {
                    res.send({ code: 1003, message: "发布失败，请稍后重试" });
                    return connection.rollback(() => {
                      console.log("插入失败数据回滚2");
                    });
                  } else {
                    connection.commit((error) => {
                      if (error) {
                        console.log("事务提交失败");
                      }
                    });
                    connection.release(); // 释放链接

                    return res.send({
                      code: 200,
                      message: "发布成功",
                      id: result1.insertId,
                      success: true,
                    }); // 返回数据库操作结果这里数据格式可根据个人或团队规范来定制
                  }
                });
              }
            });
          }
        });
      });
    }
  });
};
//更新文章
exports.updatearticle = (req, res) => {
  if (req.body.title.length < 1 || req.body.content.length < 1)
    return res.send({
      code: 1001,
      message: "标题或内容长度不合法",
    });
  if (req.body.annexname.length > 100) {
    return res.send({
      code: 1001,
      message: "附件名称长度过长",
    });
  }
  const sql = "select * from articles where id = ?";
  db.query(sql, req.body.id, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    if (result[0].authorid != req.user.id)
      return res.send({
        code: 401,
        message: "无权限修改他人文章",
      });

    db.getConnection(function (err, connection) {
      if (err) {
        return res.send({
          code: 1003,
          message: "数据库异常",
        });
      }
      connection.beginTransaction((err) => {
        //开启事务
        if (err) {
          return res.send({
            code: 1003,
            message: "数据库异常",
          });
        } else {
          let param1 = {
            title: req.body.title,
            content: req.body.content,
            annexid: req.body.annexid,
            annexname: req.body.annexname,
            annextype: req.body.annextype,
            auth: req.body.auth,
            authorid: req.user.id,
          };
          let sqlstr = "update articles set ? where id = ?";
          connection.query(
            sqlstr,
            [param1, req.body.id],
            (e, result1, fields) => {
              if (e) {
                res.send({ code: 1003, message: "更新失败，请稍后重试" });
                return connection.rollback(() => {
                  console.log("更新失败数据回滚1" + e);
                });
              } else {
                let param = {
                  isprivate: req.body.isprivate,
                  filetitle: req.body.title,
                  parentid: req.body.parentid,
                  storeid: req.body.storeid,
                  founderid: req.user.id,
                };
                const sql2 =
                  "update storefiles set ? where typeid = ? and type = 1";
                connection.query(
                  sql2,
                  [param, req.body.id],
                  (e, result2, fields) => {
                    if (e) {
                      res.send({ code: 1003, message: "更新失败，请稍后重试" });
                      return connection.rollback(() => {
                        console.log("二次更新失败数据回滚" + e);
                      });
                    } else {
                      connection.commit((error) => {
                        if (error) {
                          console.log("事务提交失败");
                        }
                      });
                      connection.release(); // 释放链接

                      return res.send({
                        code: 200,
                        message: "更新成功",
                        id: req.body.id,
                        success: true,
                      }); // 返回数据库操作结果这里数据格式可根据个人或团队规范来定制
                    }
                  }
                );
              }
            }
          );
        }
      });
    });
  });
};
//查询最近动态<全部>
exports.getallarticle = (req, res) => {
  const sql =
    "select storefiles.filetitle,storefiles.founderid,storefiles.storeid,articles.viewcount,articles.content,articles.id,articles.firstpub,storehouse.storename,user.username,user.face from articles,storehouse,user,storefiles where storefiles.status = 1 and storefiles.type = 1 and storefiles.isprivate = 0 and user.id = storefiles.founderid and storehouse.id = storefiles.storeid and storefiles.typeid = articles.id order by articles.firstpub desc";
  db.query(sql, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    for (let i = 0; i < result.length; i++) {
      result[i] = {
        id: result[i].id,
        title: result[i].filetitle,
        content: result[i].content,
        store: {
          id: result[i].storeid,
          name: result[i].storename,
        },
        author: {
          id: result[i].founderid,
          username: result[i].username,
          face: result[i].face,
        },
        viewcount: result[i].viewcount,
        first_pub: result[i].firstpub,
      };
    }
    res.send({
      code: 200,
      message: "查询所有文档动态成功",
      data: result,
    });
  });
};

//查询最火动态
exports.gethotarticle = (req, res) => {
  const sql =
    "select storefiles.filetitle,storefiles.founderid,storefiles.storeid,articles.viewcount,articles.content,articles.id,articles.firstpub,storehouse.storename,user.username,user.face from articles,storehouse,user,storefiles where storefiles.status = 1 and storefiles.type = 1 and storefiles.isprivate = 0 and user.id = storefiles.founderid and storehouse.id = storefiles.storeid and storefiles.typeid = articles.id order by articles.viewcount desc";
  db.query(sql, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    let params = [];
    for (let i = 0; i < 10 && i < result.length; i++) {
      params[i] = {
        id: result[i].id,
        title: result[i].filetitle,
        content: result[i].content,
        store: {
          id: result[i].storeid,
          name: result[i].storename,
        },
        author: {
          id: result[i].founderid,
          username: result[i].username,
          face: result[i].face,
        },
        viewcount: result[i].viewcount,
        first_pub: result[i].firstpub,
      };
    }
    res.send({
      code: 200,
      message: "查询最火动态成功",
      data: params,
    });
  });
};

//查询某个文章
exports.getsomearticle = (req, res) => {
  let userid = req.user.id;
  const sql =
    "select articles.*,storehouse.storename,storehouse.founderid,user.username,user.face,storefiles.parentid,storefiles.storeid,storefiles.isprivate from articles,storehouse,storefiles,user where articles.id = ? and articles.id = storefiles.typeid and storefiles.type = 1 and storefiles.status = 1 and user.id = articles.authorid and storehouse.id = storefiles.storeid";
  db.query(sql, req.params.id, (err, result) => {
    if (err) {
      console.log(err);
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    }

    if (result.length < 1) {
      return res.send({
        code: 404,
        message: "文章不存在",
      });
    }
    const sql2 =
      "select collectorsid from collects where articleid = ? and status = 1";
    db.query(sql2, req.params.id, (err, result1) => {
      if (err) {
        console.log(err);
        return res.send({
          code: 500,
          message: "数据库异常" + err.message,
        });
      }
      let tmp = result1.find((item) => item.collectorsid === userid);
      result[0] = {
        id: result[0].id,
        title: result[0].title,
        content: result[0].content,
        annexid: result[0].annexid,
        annexname: result[0].annexname,
        annextype: result[0].annextype,
        isprivate: result[0].isprivate,
        auth: result[0].auth,
        store: {
          id: result[0].storeid,
          name: result[0].storename,
          founderid: result[0].founderid,
        },
        author: {
          id: result[0].authorid,
          username: result[0].username,
          face: result[0].face,
        },
        viewcount: result[0].viewcount,
        first_pub: result[0].firstpub,
        last_pub: result[0].lastpub,
        parentid: result[0].parentid,
        collections: result1.length, // 收藏数量
        iscollect: tmp ? true : false, //是否被你收藏
      };
      if (result[0].isprivate == 1) {
        if (result[0].author.id != req.user.id) {
          return res.send({
            code: 1003,
            message: "暂无权限,作者可能删除",
          });
        }
      }
      const sql3 = "UPDATE articles SET viewcount = ? WHERE articles.id = ? ";
      db.query(sql3, [result[0].viewcount + 1, result[0].id], (err) => {
        if (err)
          return res.send({
            code: 500,
            message: "数据库异常" + err.message,
          });
      });
      return res.send({
        code: 200,
        message: "查询文章成功",
        data: result,
      });
    });
  });
};
//删除文章
exports.deletearticle = (req, res) => {
  const sql = "select * from articles where id = ?";
  db.query(sql, req.body.id, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    if (result[0].authorid != req.user.id)
      return res.send({
        code: 401,
        message: "无权限删除他人文章",
      });
    const sqlstr =
      "update storefiles set status = 0 where typeid = ? and type = 1";
    db.query(sqlstr, req.body.id, (err, result) => {
      if (err)
        return res.send({
          code: 500,
          message: "数据库异常" + err.message,
        });
      if (result.affectedRows !== 1)
        return res.send({
          code: 1002,
          message: "删除文章失败",
        });
      res.send({
        code: 200,
        message: "删除文章成功",
      });
    });
  });
};
//获取某人的发布文章
exports.getmypubarticle = (req, res) => {
  const sql =
    "select articles.*,storehouse.storename,storefiles.status,storefiles.storeid,user.username,user.face from articles,storehouse,user,storefiles where storefiles.status = 1 and storefiles.type = 1 and storefiles.typeid = articles.id and storefiles.isprivate = 0 and user.id = articles.authorid and storehouse.id = storefiles.storeid and articles.authorid = ? order by articles.firstpub desc";
  db.query(sql, req.params.id, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    for (let i = 0; i < result.length; i++) {
      result[i] = {
        id: result[i].id,
        title: result[i].title,
        content: result[i].content,
        store: {
          id: result[i].storeid,
          name: result[i].storename,
        },
        author: {
          id: result[i].authorid,
          username: result[i].username,
          face: result[i].face,
        },
        viewcount: result[i].viewcount,
        first_pub: result[i].firstpub,
        last_pub: result[i].lastpub,
      };
    }
    res.send({
      code: 200,
      message: "查询某人所有文章成功",
      data: result,
    });
  });
};
//通过分类获取文章
exports.getcatearticle = (req, res) => {
  const sql =
    "select articles.*,storefiles.storeid,storehouse.storename,user.username,user.face from articles,storehouse,user,storefiles where storefiles.isprivate = 0  and storefiles.status = 1 and storefiles.type = 1 and storefiles.typeid = articles.id and user.id = articles.authorid and storehouse.id = storefiles.storeid and storehouse.id = ? order by articles.firstpub desc";
  db.query(sql, req.params.id, (err, result) => {
    if (err)
      return res.send({
        code: 500,
        message: "数据库异常" + err.message,
      });
    for (let i = 0; i < result.length; i++) {
      result[i] = {
        id: result[i].id,
        title: result[i].title,
        content: result[i].content,
        store: {
          id: result[i].storeid,
          name: result[i].storename,
        },
        author: {
          id: result[i].authorid,
          username: result[i].username,
          face: result[i].face,
        },
        viewcount: result[i].viewcount,
        first_pub: result[i].firstpub,
        last_pub: result[i].lastpub,
      };
    }
    res.send({
      code: 200,
      message: "查询某分类所有文章成功",
      data: result,
    });
  });
};
//收藏文章
exports.starArticle = (req, res) => {
  let param = {
    collectorsid: req.user.id,
    articleid: req.body.articleid,
    authorid: req.body.authorid,
  };
  if (req.body.iscollect) {
    //如果是已经收藏，那就给她取消了
    const sql =
      "update collects set status = 0 where collectorsid = ? and articleid = ?";
    db.query(sql, [req.user.id, req.body.articleid], (err, result) => {
      if (err)
        return res.send({
          code: 500,
          message: "数据库异常" + err.message,
        });
      if (result.affectedRows !== 1)
        return res.send({
          code: 1002,
          message: "取消收藏失败",
        });
      return res.send({
        code: 200,
        message: "取消收藏成功",
      });
    });
  } else {
    //没收藏就收藏,先看看有没有曾经的收藏记录
    const sql1 =
      "select * from collects where collectorsid = ? and articleid = ? ";
    db.query(sql1, [req.user.id, req.body.articleid], (err, result1) => {
      if (err)
        return res.send({
          code: 500,
          message: "数据库异常" + err.message,
        });
      if (result1.length < 1) {
      // 说明第一次点收藏，那就insert，若是有的话直接把status改成1即可
        db.getConnection(function (err, connection) {
          if (err) {
            return res.send({
              code: 1003,
              message: "数据库异常",
            });
          }
          connection.beginTransaction((err) => {
            //开启事务
            if (err) {
              return res.send({
                code: 1003,
                message: "数据库异常",
              });
            } else {
              const sql2 = "insert into collects set ?";
              const sqlm = "insert into message set ?";
              connection.query(sql2, param, (e, result1) => {
                if (e) {
                  res.send({ code: 1003, message: "收藏失败，请稍后重试" });
                  console.log(e);
                  return connection.rollback(() => {
                    console.log("插入失败数据回滚1");
                  });
                } else {
                  let tmp = {
                    founderid: req.user.id,
                    articleid: req.body.articleid,
                    toUserid: req.body.authorid,
                    type: 1,
                    typeid: result1.insertId,
                  };
                  connection.query(sqlm, tmp, (e) => {
                    if (e) {
                      res.send({ code: 1003, message: "收藏失败，请稍后重试" });
                      return connection.rollback(() => {
                        console.log("插入失败数据回滚2");
                      });
                    } else {
                      connection.commit((error) => {
                        if (error) {
                          console.log("事务提交失败");
                        }
                      });
                      connection.release(); // 释放链接

                      return res.send({
                        code: 200,
                        message: "收藏成功",
                        id: result1.insertId,
                        success: true,
                      }); // 返回数据库操作结果这里数据格式可根据个人或团队规范来定制
                    }
                  });
                }
              });
            }
          });
        });
      } else {
        const sql3 =
          "update collects set status = 1 where collectorsid = ? and articleid = ? ";
        db.query(sql3, [req.user.id, req.body.articleid], (err, result3) => {
          if (err)
            return res.send({
              code: 500,
              message: "数据库异常" + err.message,
            });
          if (result3.affectedRows !== 1)
            return res.send({
              code: 1002,
              message: "收藏失败",
            });
          return res.send({
            code: 200,
            message: "收藏成功",
          });
        });
      }
    });
  }
};
